# models/models.py
from app import db
from datetime import datetime
from sqlalchemy.dialects.postgresql import JSON, ARRAY
from sqlalchemy import Text

class RawNews(db.Model):
    """原始新闻数据模型"""
    __tablename__ = 'raw_news'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(500), nullable=False)
    content = db.Column(Text, nullable=False)
    publish_date = db.Column(db.DateTime, nullable=False)
    source = db.Column(db.String(100))
    url = db.Column(db.String(500))
    processed = db.Column(db.Boolean, default=False, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def __repr__(self):
        return f'<RawNews {self.title}>'

    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'content': self.content,
            'publish_date': self.publish_date.isoformat() if self.publish_date else None,
            'source': self.source,
            'url': self.url,
            'processed': self.processed,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

class ProcessedNews(db.Model):
    """处理后的新闻数据模型"""
    __tablename__ = 'processed_news'

    id = db.Column(db.Integer, primary_key=True)
    raw_news_id = db.Column(db.Integer, db.ForeignKey('raw_news.id'), nullable=False)
    title = db.Column(db.String(500), nullable=False)
    publish_date = db.Column(db.DateTime, nullable=False)
    involved_entities = db.Column(JSON)  # 存储实体识别结果
    involved_brands = db.Column(ARRAY(db.String))  # 存储涉及的品牌
    event_description = db.Column(Text)  # 新闻摘要
    board_summary = db.Column(db.String(100))  # 看板摘要
    category = db.Column(db.String(50))  # 新闻分类
    news_score = db.Column(db.Float, default=0.0)  # 新闻评分
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关联原始新闻
    raw_news = db.relationship('RawNews', backref=db.backref('processed_news', uselist=False))

    def __repr__(self):
        return f'<ProcessedNews {self.title}>'

    def to_dict(self):
        return {
            'id': self.id,
            'raw_news_id': self.raw_news_id,
            'title': self.title,
            'publish_date': self.publish_date.isoformat() if self.publish_date else None,
            'involved_entities': self.involved_entities,
            'involved_brands': self.involved_brands,
            'event_description': self.event_description,
            'board_summary': self.board_summary,
            'category': self.category,
            'news_score': self.news_score,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

class ProcessingError(db.Model):
    """新闻处理错误记录模型"""
    __tablename__ = 'processing_errors'

    id = db.Column(db.Integer, primary_key=True)
    news_id = db.Column(db.Integer, db.ForeignKey('raw_news.id'), nullable=False)
    error_message = db.Column(Text, nullable=False)
    error_type = db.Column(db.String(100), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)

    # 关联原始新闻
    raw_news = db.relationship('RawNews', backref=db.backref('processing_errors'))

    def __repr__(self):
        return f'<ProcessingError {self.news_id}: {self.error_type}>'

    def to_dict(self):
        return {
            'id': self.id,
            'news_id': self.news_id,
            'error_message': self.error_message,
            'error_type': self.error_type,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }

class NewsCategory(db.Model):
    """新闻分类配置模型"""
    __tablename__ = 'news_categories'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True, nullable=False)
    priority = db.Column(db.Integer, default=0)  # 优先级，数值越大优先级越高
    description = db.Column(db.String(200))
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)

    def __repr__(self):
        return f'<NewsCategory {self.name}>'

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'priority': self.priority,
            'description': self.description,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
